package com.primaryedu.ui.app.parentsch;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.VoteoptionBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.CustomDialog;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投票详情
 *
 * @author Thomas
 * @description
 * @data 2018年1月8日
 */
public class VoteDetailsActivity extends BaseActivity implements OnClickListener, VoteDetailsAdapter.Callback, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener {
    private ListView listView;
    VoteDetailsAdapter adapter;
    private boolean firstenter = true;
    private List<VoteoptionBean.DataBean.ListBean> opinionLists = new ArrayList<>();
    private List<VoteoptionBean.DataBean.ListBean> opiniontempList = new ArrayList<>();
    private String voteId;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1001:
                    if (null != opiniontempList && opiniontempList.size() != 0) {
//						newsAdapter = new ExerciseAdapter(getApplicationContext(), NicedialogUtils.getExerciseList(GlobalData.newsLists)) ;
//						newsListView.setAdapter(newsAdapter);
                        adapter = new VoteDetailsAdapter(VoteDetailsActivity.this, opiniontempList, totalVoteNum, VoteDetailsActivity.this);
                        listView.setAdapter(adapter);
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };
    private VoteoptionBean.DataBean.ListBean ob;
    private CustomDialog.Builder ibuilder;
    private String totalVoteNum;
    private PullToRefreshView pullToRefreshView;
    private String endtime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_vote_details);


    }

    private void getOptionListJson(boolean firstenter) {
        if (firstenter) {
            showLoading("加载中...");
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.voteoptionList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=voteoptionlist=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                totalVoteNum = listObj.getString("totalVoteNum");
                                Log.i("yy", "onResponse: totalVoteNum======" + totalVoteNum);
                                String listStr = listObj.getString("list");
                                opinionLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<VoteoptionBean.DataBean.ListBean>>() {
                                        }.getType());
//
                                opiniontempList.clear();
                                opiniontempList.addAll(opinionLists);
                                handler.sendEmptyMessage(1001);
//								System.out.println("VoteoptionBeanVoteoptionBean="+listStr);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("voteId", voteId);
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }


    @Override
    protected int BindLayout() {
        return R.layout.activity_vote_details;
    }

    @Override
    protected void initView() {
        ((TextView) findViewById(R.id.title)).setText("投票详情");
        findViewById(R.id.back).setOnClickListener(this);
        Intent intent = getIntent();
        //id
        voteId = intent.getStringExtra("id");
        Log.i("yy", "init: voteId=====" + voteId);
        //endtime 截止时间
        endtime = intent.getStringExtra("endtime");
        Log.i("yy", "init: endtime=====" + endtime);

        listView = (ListView) this.findViewById(R.id.listView);
//		listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        pullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected void initData() {
        getOptionListJson(true);
    }

    /**
     * 接口方法，响应ListView按钮点击事件
     */
    @Override
    public void click(View v) {
//		 showToast("投票成功" + v.getTag());
        Log.i("yy", "init: getCurrentDateTwo=====" + Utils.getCurrentDateTwo().toString());
        if (Utils.isDate2Bigger(Utils.getCurrentDateTwo(),endtime)) {
            ob = opiniontempList.get((Integer) v.getTag());
            showtrueDialog("投票", "您确定要投票给他吗？");
        }else {
            showToast("投票时间已过，无法投票");
        }
        //投票
//		 getuserVote();

    }

    private void getuserVote() {
        showLoading("投票中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.voteuser,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=voteuser=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                showToast("投票成功");
                                getOptionListJson(true);
                            } else if (result == 0) {
                                showToast("您已经投过票了，无法重复投票！");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("投票失败，请重新投票！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("userId", GlobalData.getUserId(getApplicationContext()));
                map.put("userName", GlobalData.getUsername(getApplicationContext()));
                map.put("voteOptionId", ob.getId());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            default:
                break;
        }

    }

    private void showtrueDialog(String title, String content) {
        ibuilder = new CustomDialog.Builder(this);
        ibuilder.setTitle(title);
        ibuilder.setMessage(content);
        ibuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        ibuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getuserVote();
            }
        });

        Dialog dialog = ibuilder.create();
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.8);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
//				uploadMore = true;

                getOptionListJson(false);
                pullToRefreshView.onFooterRefreshComplete();

            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                getOptionListJson(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(VoteDetailsActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }
}
